package com.ll.blog.aspect;


import com.ll.blog.annotation.Record;
import com.ll.blog.common.IPUtils;
import com.ll.blog.contant.BehaviorEnum;
import com.ll.blog.entity.Behavior;
import com.ll.blog.service.IBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Order(2)
@Slf4j
public class recordAspect {
    @Resource
    IBehaviorService behaviorService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Pointcut("@annotation(com.ll.blog.annotation.Record)")
    public void pointcut(){}

    @Around("pointcut() && @annotation(record)")
    public Object around(ProceedingJoinPoint pjp, Record record) throws Throwable {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = IPUtils.getIpAddr(request);
        BehaviorEnum type = record.type();
        if (operations.get(type.getDesc()+"-"+ip)!=null){
            return pjp.proceed();
        }
        String id =null;
        if (type==BehaviorEnum.ARTICLE_MODULE){
            String requestURI = request.getRequestURI();
            id = requestURI.split("/")[3];
        }
        Behavior behavior = new Behavior();
        behavior.setAction(id);
        behavior.setIp(ip);
        behavior.setType(type);
        boolean saved = behaviorService.save(behavior);
        if (!saved){
            log.error("行为记录失败"+ LocalDateTime.now());
        }
        operations.set(type.getDesc()+"-"+ip,ip,record.time(), TimeUnit.MINUTES);
        return pjp.proceed();
    }
}
